package com.unibeta.cloudtest.mesher.auth.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.unibeta.cloudtest.mesher.auth.annotation.Authorization;
import com.unibeta.cloudtest.mesher.auth.service.AuthorizationService;

import lombok.extern.slf4j.Slf4j;

@Configuration
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

//	@Autowired
//	RedisRepository redis;

	@Autowired
	AuthorizationService authorizationService;

	@Override
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Object object) throws Exception {

//		if (!com.unibeta.cloudtest.mesher.config.Configuration.isAuthorizationEnabled()) {
//			return true;
//		}

		if (!(object instanceof HandlerMethod)) {
			return true;
		}

		HandlerMethod handlerMethod = (HandlerMethod) object;
		Method method = handlerMethod.getMethod();
		Class clazz = handlerMethod.getBeanType();

		Authorization methodAntuorized = method.getAnnotation(Authorization.class);
		Authorization classAntuorized = (Authorization) clazz.getAnnotation(Authorization.class);

		if ((classAntuorized != null && classAntuorized.required())
				|| (null != methodAntuorized && methodAntuorized.required())) {

			String authToken = httpServletRequest.getHeader(Authorization.NAME);
			String token = httpServletRequest.getHeader(Authorization.TOKEN);

			if (authToken != null) {
				String[] tk = authToken.split(Authorization.BEARER);
				if (tk.length == 2 && !StringUtils.isEmpty(tk[1])) {
					token = tk[1];
				}

				if (!StringUtils.isEmpty(token)) {
					try {
						authorizationService.authToken(token);
					} catch (Exception e) {
						
						log.debug(e.getMessage());
						
						httpServletResponse.setStatus(401, e.getMessage());
						return false;
					}
					
				} else {
					httpServletResponse.setStatus(401, "accessing token is required.");
					return false;
				}
			} else {
				httpServletResponse.setStatus(401, "accessing token is required.");
				return false;
			}
		}

		return true;
	}
	
}
